#include <head.h>

int main(int argc, char const *argv[])
{
    // 1 创建套接字
    int sok_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (sok_fd == -1)
    {
        perror("socket");
        exit(1);
    }
    // 绑定
    struct sockaddr_in sok_addr;
    sok_addr.sin_family = AF_INET;
    sok_addr.sin_port = htons(8077);
    sok_addr.sin_addr.s_addr = inet_addr("192.168.10.248");
    socklen_t len = sizeof(sok_addr);
    if (bind(sok_fd, (struct sockaddr *)&sok_addr, len) == -1)
    {
        perror("bind");
        exit(-1);
    }
    // 监听
    if (listen(sok_fd, 5) == -1)
    {
        perror("listen");
        exit(-1);
    }
    // 阻塞等待客户端连接
    printf("等待客户端连接\n");
    int sok_acc = accept(sok_fd, NULL, NULL);
    if (sok_acc == -1)
    {
        perror("accept");
        exit(-1);
    }
    printf("客户端连接成功\n");

    // 数据收发
    char buf[128];
    printf("开始聊天\n");
    while (1)
    {
        memset(buf, 0, sizeof(buf));
        printf("服务端输入:");
        fgets(buf, sizeof(buf), stdin);
        if (!strcmp(buf, "quit"))
        {
            printf("退出成功\n");
            write(sok_fd, buf, strlen(buf));
            close(sok_fd);
            close(sok_acc);
            return 0;
        }
        write(sok_acc, buf, sizeof(buf));
        memset(buf, 0, sizeof(buf));
        read(sok_acc, buf, sizeof(buf));
        printf("客户端输入: %s\n",buf);

    }
    //
    close(sok_fd);
    close(sok_acc);

    return 0;
}
